/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
/**
 * 分类界面
 * @type {*|exports|module.exports}
 */
var React = require('react');
var {
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    ListView,
    Image,
    BackAndroid,
    ScrollView,
    Animated,
    PixelRatio,
    Dimensions,
    Alert,
    Easing,
    Modal,
    TouchableOpacity,
    ActivityIndicator,
    AsyncStorage
} = require('react-native');

import Imagez from 'react-native-image-progress';
import NavTitle from '../component/NavTitle';
import Communications from '../utils/Communications';

import XFetch from '../XFetch';
import ContactServicer from './ContactServicer';

import ProductShops from './ProductShops';
import SearchBar from 'antd-mobile/lib/search-bar';

var ds;

class Classify extends React.Component {
    // 构造函数
    constructor(props) {
        super(props);
        // 初始状态
        ds = new ListView.DataSource({
          rowHasChanged: (r1, r2) => r1 !== r2
        });
        this.state =  {
            animating:false,
            dataLeftSource: ds.cloneWithRows([]),
            rightData:ds.cloneWithRows([]),
        };
    }
    componentDidMount() {
          this.setState({
              dataLeftSource:ds.cloneWithRows([1,2,3,4,5,6,7,8,9])
          });
        this._changeAddress();
        this._getGoods(this.props.id,null,null);
    }

    _contactService(){
        this.props.navigator.push({
            name:'ContactServicer',
            component:ContactServicer
        })
    }

    _changeAddress(){
        this.setState({
            animating:true,
        })
        XFetch(`http://www.weiweigo.com/app/type.aspx?method=show&chnId=2&pid=0`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                rightData:ds.cloneWithRows(data[0].childList),
                animating:false,
            })
        });
    }

    _getGoods(aid,cid,key){
        let _p = '&';
        if(aid){
            _p+='aid='+aid+'&';
        }
        if(cid){
            _p+='cid='+cid+'&';
        }
        if(key){
            _p+='key='+key+'&';
        }
        XFetch(`http://www.weiweigo.com/app/shop.aspx?method=listByPage${_p}`,{
            method:'GET',
        }).then(data=>{
            this.setState({
                dataLeftSource:ds.cloneWithRows(data.data),
                animating:false,
            })
        });
    }

    _allShops(){
        this._getGoods(this.props.id,null,null);
    }

    _onRightClassify(data){
        this._getGoods(this.props.id,data.classId,null);
    }

    _onLeftSHop(data){
        this.props.navigator.push({
            name:'ProductShops',
            component:ProductShops,
            params:{
                id:data.shopId
            }
        })
    }

    _search(val){
        this._getGoods(this.props.id,null,val);
    }

    render() {

        return (
            <View style={styles.wrap}>
                <NavTitle
                  title='同城商家'
                  headColor = '#fbdc3a'
                  leftButton = {true}
                  leftImg = {require('../imgs/left.png')}
                  leftHander = {()=>{this.props.navigator.pop()}}
                  rightImg={require('../imgs/search.jpg')}
                  rightHander={this._showSearch.bind(this)}
                />
                <SearchBar placeholder="搜索" onSubmit={this._search.bind(this)}/>
                <View>
                    <Image style={styles.topAd} resizeMode={'contain'} source={{uri:'http://www.weiweigo.com/images/m_ad.jpg'}}></Image>
                </View>
                <View style={styles.container}>
                      <View style={styles.rightContent}>
                        <ListView
                            horizontal={false}
                            showsHorizontalScrollIndicator={false}
                            showsVerticalScrollIndicator = {false}
                            removeClippedSubviews = {true}
                            dataSource={this.state.dataLeftSource}
                            renderRow={this._renderLeftRowView.bind(this)}
                            enableEmptySections={true}
                            scrollRenderAheadDistance={5} />
                      </View>
                      <View style={styles.leftMenu}>
                          <TouchableOpacity onPress={this._allShops.bind(this)} style={{height: 44,justifyContent:'center',alignItems:'flex-start',paddingLeft:10,borderBottomWidth:1/PixelRatio.get(),borderColor:'#E0E0E0'}}>
                              <Text style={{fontSize:14,color:'#666',justifyContent:'center',alignItems:'center'}}>全部</Text>
                          </TouchableOpacity>
                          <ListView
                              horizontal={false}
                              showsHorizontalScrollIndicator={false}
                              showsVerticalScrollIndicator = {false}
                              removeClippedSubviews = {true}
                              dataSource={this.state.rightData}
                              renderRow={this._renderRightRowView.bind(this)}
                              enableEmptySections={true}
                              scrollRenderAheadDistance={5} />
                      </View>
                </View>
                <ActivityIndicator
                    toast
                    text="数据加载中..."
                    animating={this.state.animating}
                />
            </View>
        );
    }

    _renderRightRowView(rowData,sectionID,rowId) {
          return (
              <TouchableHighlight
                  style={{height: 48,justifyContent:'center',alignItems:'flex-start',paddingLeft:10,borderBottomWidth:1/PixelRatio.get(),borderColor:'#E0E0E0'}}
                  underlayColor='#c8c7cc'
                  onPress={this._onRightClassify.bind(this,rowData)}
              >
                  <View style={{justifyContent:'center',alignItems:'center',flexDirection:'row'}}>
                      <Text numberOfLines={1} style={{fontSize:14,color:'#666',width:66,justifyContent:'center',alignItems:'center'}} >
                          {rowData.className}
                      </Text>
                  </View>
              </TouchableHighlight>
          );

    }
    _renderLeftRowView(rowData,sectionID,rowId) {
        return (
            <TouchableHighlight
                underlayColor='#c8c7cc'
                key={rowId}
                onPress={this._onLeftSHop.bind(this,rowData)}>
                <View style={styles.item}>
                    <Imagez
                        style={styles.userLogo}
                        resizeMode="contain"
                        source={{uri:`http://www.weiweigo.com${rowData.imgUrl}`}}
                        defaultSource={require('../imgs/default_image.png')}
                    />
                    <View style={styles.describe}>
                      <Text numberOfLines={1} style={styles.title} >
                          {rowData.title}
                      </Text>
                      <Text numberOfLines={2} style={styles.detail} >
                          {rowData.summary}
                      </Text>
                    </View>
                    <TouchableOpacity
                      underlayColor='#c8c7cc'
                      style={styles.right}
                      onPress={() => Communications.phoneCall(rowData.tel,false)}
                    >
                        <Image source={require('../imgs/icPhoneSmallRed.png')} style={styles.phone}/>
                    </TouchableOpacity>
                </View>
            </TouchableHighlight>
        );
    }
    _onPress(rowData){

    }
};

var styles = {
    wrap: {
        flex: 1,
        backgroundColor: '#FFF',
    },
    container:{
        flex:1,
        flexDirection:'row',
        backgroundColor:'#F5F5F5',
    },
    topAd:{
        width:Dimensions.get('window').width,
        height:100
    },
    leftMenu:{
        backgroundColor:'#F0F0F0',
        width:96,
        borderColor:'#E0E0E0',
        borderRightWidth:1/PixelRatio.get()
    },
    rightContent:{
        flexDirection:'column',
        flex:2
    },
    item:{
        flexDirection:'row',
        paddingLeft:10,
        paddingTop:10,
        paddingRight:10,
        paddingBottom:10,
        borderBottomWidth:1,
        borderColor:'#CCC'
    },
    userLogo:{
        width:30,
        height:30,
        borderRadius:15,
        alignSelf:'center'
    },
    describe:{
        flex:1,
        justifyContent:'flex-start',
        marginLeft:10,
        marginRight:5
    },
    title:{
      color:'#666',
      fontSize:16
    },
    detail:{
      marginTop:10,
      color:'#999',
      fontSize:14
    },
    right:{
        width:20,
        justifyContent:'center',
        alignItems:'center',
        alignSelf:'center'
    },
    phone:{
        width:20,
        height:20
    }
};

module.exports = Classify;
